package router

import (
	"encoding/json"
	"fmt"
	"net/http"

	"go-learn/go_learn/prometheus/web_hook/global"
	"go-learn/go_learn/prometheus/web_hook/middleware"
	"go-learn/go_learn/prometheus/web_hook/model"
	"go-learn/go_learn/prometheus/web_hook/notifier"

	"github.com/gin-gonic/gin"
)

func NewRouter() *gin.Engine {
	r := gin.New()

	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	r.Use(middleware.ContextTimeOut(global.ServerSetting.ContextTimeout))

	r.POST("/webhook", func(c *gin.Context) {
		// data, _ := ioutil.ReadAll(c.Request.Body)
		// fmt.Printf("ctx.Request.body: %v", string(data))
		var notification model.Notification
		err := c.BindJSON(&notification)
		bs, _ := json.Marshal(notification)
		fmt.Println(string(bs))
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		err = notifier.Send(notification)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		}
		c.JSON(http.StatusOK, gin.H{"message": "send to dingtalk successful!"})
	})
	return r
}
